package com.lanou3g.k12.web.controller;

import com.github.pagehelper.Page;
import com.lanou3g.k12.entity.User;
import com.lanou3g.k12.service.UserService;
import com.lanou3g.k12.utils.K12Result;
import com.lanou3g.k12.utils.K12ResultUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;

@RestController
public class UserController {
    @Autowired
    private UserService userService;

    //获取用户列表
    @GetMapping("/users")
    //分页功能
    public K12Result findAllUser(@RequestParam(value = "page", defaultValue = "1") Integer page,
                                 String keyword,
                                 @RequestParam(value = "size", defaultValue = "10") Integer size) {
        try {
            Page all;
            if (keyword != null && !keyword.trim().equals("")) {
                //关键字查询
                all = userService.search(page, keyword, size);
            } else {
                //查询所有
                all = userService.findAllUser(page, size);
            }
            return K12ResultUtils.ok(all);
        } catch (Exception e) {
            e.printStackTrace();
            return K12ResultUtils.error(533);
        }
    }

    //用户注册
    @PostMapping("/user")
    public K12Result insertUser(User user) {
        try {
            userService.insertUser(user);
            return K12ResultUtils.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return K12ResultUtils.error(500);
        }
    }

    //通过ID删除用户
    @DeleteMapping("/user/{id}")
    public K12Result deleteUserById(@PathVariable Long id) {
        try {
            userService.deleteUserById(id);
            return K12ResultUtils.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return K12ResultUtils.error(500);
        }
    }

    // 通过ID获取用户
    @GetMapping("/user/{id}")
    public K12Result findUserById(@PathVariable Long id) {
        try {
            List <User> userById = userService.findUserById(id);
            return K12ResultUtils.ok(userById);
        } catch (Exception e) {
            e.printStackTrace();
            return K12ResultUtils.error(533);
        }

    }

    // 通过ID修改用户
    @PutMapping("/user/{id}")
    public K12Result updateUserById(@PathVariable Long id, User user) {


        userService.updateUserById(id, user);
        try {
            return K12ResultUtils.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return K12ResultUtils.error(500);
        }
    }

    // 通过ID批量删除用户
    @DeleteMapping("/users/{ids}")
    public K12Result deleteByIds(@PathVariable Integer[] ids) {

        userService.deleteByIds(ids);

        return K12ResultUtils.ok();
    }


    // 根据id批量导出数据
    @GetMapping("/user/export/{ids}")
    public void exportByIds(@PathVariable Integer[] ids, HttpServletResponse response) throws IOException {

        response.reset();
        response.setContentType("application/msexcel;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode("用户信息表.xls", "UTF-8"));
        InputStream inputStream = userService.exportByIds(ids);
        IOUtils.copy(inputStream,response.getOutputStream());

    }
//    修改密码
    @PutMapping("/updatePwd/{id}")
    public K12Result updatePwd(User user){
        try{
            userService.updatePwd(user);
            return K12ResultUtils.ok();
        }catch (Exception e){
            e.printStackTrace();
            return K12ResultUtils.error(533);
        }

    }

    // 用户登录
    @GetMapping("/userLogin")
    public K12Result login(String phone, String password, HttpServletRequest request) {
        try {
            String login = userService.login(phone, password);
            HttpSession session = request.getSession();
            if (login.equals(phone)){
                session.setAttribute("phone",phone);
            }
            return K12ResultUtils.ok(login);
        } catch (Exception e) {
            e.printStackTrace();
            return K12ResultUtils.error(533);
        }
    }
    //    用户退出登录
    @GetMapping("/quit")
    public K12Result quit(HttpServletRequest request){
        HttpSession session = request.getSession();
        session.invalidate();
        return K12ResultUtils.ok();
    }
    // 完善用户信息
    @PutMapping("/perfectUser/{phone}")
    public K12Result PerfectUser(User user,@PathVariable String phone,HttpServletRequest request){
        try {
            if (request.getSession().getAttribute("phone") != null){
                String s = userService.perfectUser(user);
                if (s.equals("成功")){
                    return K12ResultUtils.ok(user);
                }else {
                    return K12ResultUtils.ok(s);
                }
            }else {
                return K12ResultUtils.ok("还没登陆，请先登录");
            }

        } catch (Exception e) {
            e.printStackTrace();
            return K12ResultUtils.error(533);
        }
    }
}
